{% extends 'base.html' %}

{% block title %}{{ consumable.name }} - 耗材记录 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    /* 现代化设计样式 */
    .record-card {
        background: white;
        border-radius: 15px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        border: none;
    }
    
    .record-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }
    
    .consumable-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px 15px 0 0;
        padding: 2rem;
    }
    
    .stock-indicator {
        display: inline-flex;
        align-items: center;
        padding: 0.5rem 1rem;
        border-radius: 25px;
        font-weight: 600;
        font-size: 0.9rem;
    }
    
    .stock-normal {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
    }
    
    .stock-low {
        background: linear-gradient(135deg, #fc466b, #3f5efb);
        color: white;
    }
    
    .stock-out {
        background: linear-gradient(135deg, #434343, #000000);
        color: white;
    }
    
    /* 记录时间轴样式 */
    .timeline {
        position: relative;
        padding-left: 2rem;
    }
    
    .timeline::before {
        content: '';
        position: absolute;
        left: 1rem;
        top: 0;
        bottom: 0;
        width: 2px;
        background: linear-gradient(to bottom, #667eea, #764ba2);
    }
    
    .timeline-item {
        position: relative;
        margin-bottom: 2rem;
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
    }
    
    .timeline-item:hover {
        transform: translateX(5px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .timeline-item::before {
        content: '';
        position: absolute;
        left: -2.5rem;
        top: 1.5rem;
        width: 1rem;
        height: 1rem;
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 0 0 3px #667eea;
    }
    
    .timeline-item.in::before {
        background: #28a745;
        box-shadow: 0 0 0 3px #28a745;
    }
    
    .timeline-item.out::before {
        background: #dc3545;
        box-shadow: 0 0 0 3px #dc3545;
    }
    
    /* 快速操作面板 */
    .quick-actions {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .action-btn {
        border-radius: 10px;
        padding: 0.75rem 1.5rem;
        font-weight: 600;
        transition: all 0.3s ease;
        border: none;
        margin: 0.25rem;
    }
    
    .action-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }
    
    .btn-stock-in {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }
    
    .btn-stock-out {
        background: linear-gradient(135deg, #dc3545, #fd7e14);
        color: white;
    }
    
    /* 统计卡片 */
    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        border: none;
    }
    
    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(0,0,0,0.15);
    }
    
    .stat-number {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
    }
    
    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
        font-weight: 500;
    }
    
    /* 响应式设计 */
    @media (max-width: 768px) {
        .consumable-header {
            padding: 1.5rem;
        }
        
        .timeline {
            padding-left: 1.5rem;
        }
        
        .timeline::before {
            left: 0.75rem;
        }
        
        .timeline-item::before {
            left: -2rem;
        }
        
        .quick-actions {
            padding: 1rem;
        }
        
        .action-btn {
            width: 100%;
            margin: 0.25rem 0;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
            <li class="breadcrumb-item"><a href="{% url 'assets:consumable_list' %}">耗材管理</a></li>
            <li class="breadcrumb-item"><a href="{% url 'assets:consumable_detail' consumable.pk %}">{{ consumable.name }}</a></li>
            <li class="breadcrumb-item active" aria-current="page">记录管理</li>
        </ol>
    </nav>

    <!-- 耗材信息头部 -->
    <div class="record-card mb-4">
        <div class="consumable-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h2 class="mb-2">
                        <i class="fas fa-box me-2"></i>{{ consumable.name }}
                    </h2>
                    <p class="mb-2 opacity-75">
                        <i class="fas fa-barcode me-2"></i>{{ consumable.code }}
                        {% if consumable.description %}
                        <span class="ms-3">
                            <i class="fas fa-info-circle me-1"></i>{{ consumable.description|truncatechars:20 }}
                        </span>
                        {% endif %}
                    </p>
                    <div class="d-flex align-items-center">
                        {% if consumable.quantity <= 0 %}
                        <span class="stock-indicator stock-out">
                            <i class="fas fa-exclamation-triangle me-1"></i>缺货
                        </span>
                        {% elif consumable.quantity <= consumable.min_quantity %}
                        <span class="stock-indicator stock-low">
                            <i class="fas fa-exclamation-circle me-1"></i>库存不足
                        </span>
                        {% else %}
                        <span class="stock-indicator stock-normal">
                            <i class="fas fa-check-circle me-1"></i>库存正常
                        </span>
                        {% endif %}
                        <span class="ms-3 opacity-75">
                            当前库存: <strong>{{ consumable.quantity }} {{ consumable.unit }}</strong>
                        </span>
                    </div>
                </div>
                <div class="col-md-4 text-end">
                    <div class="d-flex flex-column align-items-end">
                        <div class="mb-2">
                            <span class="opacity-75">库存价值</span>
                        </div>
                        <div class="h3 mb-0">
                            {% widthratio consumable.quantity 1 consumable.purchase_price as stock_value %}
                            ¥{{ stock_value|floatformat:2 }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 左侧主要内容 -->
        <div class="col-lg-8">
            <!-- 快速操作面板 -->
            <div class="quick-actions">
                <h5 class="mb-3">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h5>
                <div class="d-flex flex-wrap">
                    <button type="button" class="btn action-btn btn-stock-in" data-bs-toggle="modal" data-bs-target="#stockInModal">
                        <i class="fas fa-arrow-down me-2"></i>入库操作
                    </button>
                    <button type="button" class="btn action-btn btn-stock-out" data-bs-toggle="modal" data-bs-target="#stockOutModal">
                        <i class="fas fa-arrow-up me-2"></i>出库操作
                    </button>
                    <button type="button" class="btn action-btn btn-outline-primary" onclick="exportRecords()">
                        <i class="fas fa-download me-2"></i>导出记录
                    </button>
                    <button type="button" class="btn action-btn btn-outline-info" onclick="printLabel()">
                        <i class="fas fa-print me-2"></i>打印标签
                    </button>
                </div>
            </div>

            <!-- 记录时间轴 -->
            <div class="record-card">
                <div class="card-header bg-transparent border-0 pb-0">
                    <h5 class="mb-0">
                        <i class="fas fa-history me-2"></i>操作记录
                        <small class="text-muted ms-2">(最近 {{ records.count }} 条记录)</small>
                    </h5>
                </div>
                <div class="card-body">
                    {% if records %}
                    <div class="timeline">
                        {% for record in records %}
                        <div class="timeline-item {{ record.transaction_type }}" data-record-id="{{ record.id }}">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div class="d-flex align-items-center">
                                    {% if record.transaction_type == 'in' %}
                                    <span class="badge bg-success me-2">
                                        <i class="fas fa-arrow-down me-1"></i>入库
                                    </span>
                                    {% else %}
                                    <span class="badge bg-danger me-2">
                                        <i class="fas fa-arrow-up me-1"></i>出库
                                    </span>
                                    {% endif %}
                                    <div>
                                        <div class="fw-bold">
                                            {% if record.transaction_type == 'in' %}
                                            <span class="text-success">+{{ record.quantity }}</span>
                                            {% else %}
                                            <span class="text-danger">-{{ record.quantity }}</span>
                                            {% endif %}
                                            <span class="text-muted ms-1">{{ consumable.unit }}</span>
                                        </div>
                                        <small class="text-muted">
                                            余额: {{ record.remaining_quantity|default:"-" }} {{ consumable.unit }}
                                        </small>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <div class="text-muted small">
                                        {{ record.created_at|date:"Y-m-d H:i" }}
                                    </div>
                                    {% if record.operator %}
                                    <div class="text-muted small">
                                        <i class="fas fa-user me-1"></i>{{ record.operator.get_full_name|default:record.operator.username }}
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            {% if record.description %}
                            <div class="mt-2">
                                <div class="alert alert-light mb-0 py-2">
                                    <i class="fas fa-comment me-2 text-muted"></i>{{ record.description }}
                                </div>
                            </div>
                            {% endif %}
                            
                            {% if record.operator == request.user %}
                            <div class="mt-2 text-end">
                                <button type="button" class="btn btn-outline-primary btn-sm" 
                                        onclick="editDescription({{ record.id }})">
                                    <i class="fas fa-edit me-1"></i>编辑
                                </button>
                                <button type="button" class="btn btn-outline-danger btn-sm" 
                                        onclick="deleteRecord({{ record.id }})">
                                    <i class="fas fa-trash me-1"></i>删除
                                </button>
                            </div>
                            {% endif %}
                        </div>
                        {% endfor %}
                    </div>
                    
                    <!-- 加载更多 -->
                    {% if has_more_records %}
                    <div class="text-center mt-4">
                        <button type="button" class="btn btn-outline-primary" onclick="loadMoreRecords()">
                            <i class="fas fa-chevron-down me-2"></i>加载更多记录
                        </button>
                    </div>
                    {% endif %}
                    {% else %}
                    <div class="text-center py-5">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">暂无操作记录</h5>
                        <p class="text-muted">开始第一次入库或出库操作吧</p>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#stockInModal">
                            <i class="fas fa-plus me-2"></i>添加记录
                        </button>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 右侧统计信息 -->
        <div class="col-lg-4">
            <!-- 统计概览 -->
            <div class="row mb-4">
                <div class="col-6">
                    <div class="stat-card">
                        <div class="stat-number text-success">{{ total_in_quantity|default:0 }}</div>
                        <div class="stat-label">总入库量</div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-card">
                        <div class="stat-number text-danger">{{ total_out_quantity|default:0 }}</div>
                        <div class="stat-label">总出库量</div>
                    </div>
                </div>
            </div>
            
            <div class="row mb-4">
                <div class="col-6">
                    <div class="stat-card">
                        <div class="stat-number text-primary">{{ total_in_count|default:0 }}</div>
                        <div class="stat-label">入库次数</div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-card">
                        <div class="stat-number text-warning">{{ total_out_count|default:0 }}</div>
                        <div class="stat-label">出库次数</div>
                    </div>
                </div>
            </div>

            <!-- 库存趋势图 -->
            <div class="record-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-line me-2"></i>库存趋势
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="stockTrendChart" height="200"></canvas>
                </div>
            </div>

            <!-- 最近活动 -->
            <div class="record-card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-clock me-2"></i>最近活动
                    </h6>
                </div>
                <div class="card-body">
                    {% if recent_activities %}
                    <div class="list-group list-group-flush">
                        {% for activity in recent_activities %}
                        <div class="list-group-item border-0 px-0">
                            <div class="d-flex align-items-center">
                                {% if activity.transaction_type == 'in' %}
                                <i class="fas fa-arrow-down text-success me-2"></i>
                                {% else %}
                                <i class="fas fa-arrow-up text-danger me-2"></i>
                                {% endif %}
                                <div class="flex-grow-1">
                                    <div class="fw-bold">{{ activity.get_transaction_type_display }}</div>
                                    <small class="text-muted">{{ activity.created_at|timesince }}前</small>
                                </div>
                                <div class="text-end">
                                    <div class="fw-bold">
                                        {% if activity.transaction_type == 'in' %}+{% else %}-{% endif %}{{ activity.quantity }}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-clock fa-2x mb-2"></i>
                        <p class="mb-0">暂无最近活动</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 入库模态框 -->
<div class="modal fade" id="stockInModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-arrow-down me-2 text-success"></i>入库操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="{% url 'assets:consumable_detail' consumable.pk %}"
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="inQuantity" class="form-label">入库数量</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="inQuantity" name="quantity" 
                                   min="0.01" step="0.01" required>
                            <span class="input-group-text">{{ consumable.unit }}</span>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="inDescription" class="form-label">操作说明</label>
                        <textarea class="form-control" id="inDescription" name="description" rows="3" 
                                  placeholder="请输入入库原因或说明..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check me-1"></i>确认入库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 出库模态框 -->
<div class="modal fade" id="stockOutModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-arrow-up me-2 text-danger"></i>出库操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="{% url 'assets:consumable_detail' consumable.pk %}"
                {% csrf_token %}
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        当前库存: <strong>{{ consumable.quantity }} {{ consumable.unit }}</strong>
                    </div>
                    <div class="mb-3">
                        <label for="outQuantity" class="form-label">出库数量</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="outQuantity" name="quantity" 
                                   min="0.01" max="{{ consumable.quantity }}" step="0.01" required>
                            <span class="input-group-text">{{ consumable.unit }}</span>
                        </div>
                        <div class="form-text">最大可出库: {{ consumable.quantity }} {{ consumable.unit }}</div>
                    </div>
                    <div class="mb-3">
                        <label for="outDescription" class="form-label">操作说明</label>
                        <textarea class="form-control" id="outDescription" name="description" rows="3" 
                                  placeholder="请输入出库原因或说明..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-check me-1"></i>确认出库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑描述模态框 -->
<div class="modal fade" id="editDescriptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit me-2"></i>编辑记录描述
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" id="editDescriptionForm">
                {% csrf_token %}
                <input type="hidden" name="action" value="edit_description">
                <input type="hidden" name="record_id" id="editRecordId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="editDescription" class="form-label">记录描述</label>
                        <textarea class="form-control" id="editDescription" name="description" rows="4" 
                                  placeholder="请输入操作描述..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 库存趋势图
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('stockTrendChart').getContext('2d');
    
    // 模拟数据，实际应该从后端获取
    const trendData = {
        labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
        datasets: [{
            label: '库存量',
            data: [120, 100, 80, 90, 110, {{ consumable.quantity }}],
            borderColor: '#667eea',
            backgroundColor: 'rgba(102, 126, 234, 0.1)',
            tension: 0.4,
            fill: true
        }]
    };
    
    new Chart(ctx, {
        type: 'line',
        data: trendData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0,0,0,0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
});

// 编辑描述
function editDescription(recordId) {
    const modal = new bootstrap.Modal(document.getElementById('editDescriptionModal'));
    const record = document.querySelector(`[data-record-id="${recordId}"]`);
    const descriptionElement = record.querySelector('.alert');
    const currentDescription = descriptionElement ? descriptionElement.textContent.trim().replace(/^.*?/, '') : '';
    
    document.getElementById('editRecordId').value = recordId;
    document.getElementById('editDescription').value = currentDescription;
    
    modal.show();
}

// 删除记录
function deleteRecord(recordId) {
    if (confirm('确定要删除这条记录吗？')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            {% csrf_token %}
            <input type="hidden" name="action" value="delete_record">
            <input type="hidden" name="record_id" value="${recordId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// 导出记录
function exportRecords() {
    window.location.href = '{% url "assets:inventory_log_list" %}?export=excel&consumable=' + {{ consumable.pk }};
}

// 打印标签
function printLabel() {
    alert('打印标签功能开发中...');
}

// 加载更多记录
function loadMoreRecords() {
    // 实现AJAX加载更多记录
    console.log('加载更多记录...');
}

// 实时更新库存状态
function updateStockStatus() {
    // 实现实时库存状态更新
    fetch('/api/consumables/' + {{ consumable.pk }} + '/status/')
        .then(response => response.json())
        .then(data => {
            // 更新页面上的库存信息
            console.log('库存状态已更新', data);
        })
        .catch(error => {
            console.error('更新库存状态失败:', error);
        });
}

// 每30秒更新一次库存状态
setInterval(updateStockStatus, 30000);
</script>
{% endblock %}